package com.yc.spring.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Component("myAspect")
@Aspect  // 切面类 = 切点 + 增强
public class MyAspect {

    // 日志输出
    @Before("execution(* com.yc.spring..biz.*Biz.create(..))")
    // 接口注入连接点  ==> 方法信息
    public void before(JoinPoint jp){
        System.out.println("jp.getSignature() = " + jp.getSignature());
        System.out.println("jp.getArgs() = " + jp.getArgs());
    }

    // 切点方法
    @Pointcut("execution(* com.yc.spring..biz.*Biz.modify(..))")
    public void pointcut(){}

    @Before("pointcut()")  // 引用切点
    public void before1(JoinPoint jp){
        System.out.println("============ Before ==========" + jp.getSignature());
    }

    @After("pointcut()")  // 引用切点
    public void after(JoinPoint jp){
        System.out.println("============ After ==========" + jp.getSignature());
    }

    // 返回增强, 业务方法正常执行结束, 返回结果,  ret=>业务方法返回结果
    @AfterReturning(value = "pointcut()", returning = "ret") // 引用切点
    public void returning(JoinPoint jp, Object ret){
        System.out.println("============ AfterReturning ==========" + jp.getSignature() + " : " + ret);
    }

    // 异常增强, 业务方法出现异常, 执行的增项
    @AfterThrowing(value = "pointcut()", throwing = "t")
    public  void throwing(JoinPoint jp, Throwable t){
        System.out.println("============ AfterThrowing ==========" + jp.getSignature() + " : " + t);
    }

    /**
     * 环绕增强与普通增强不同
     * 1. 连接点对象不同, 业务方法需要手动执行
     * 2. 增强方法的返回值, 就是业务方法的返回值
     * @param pjp
     */
    @Around("pointcut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        Object ret = null;
        try {
            System.out.println("============ Around ==========" + pjp.getSignature());
            long time = System.currentTimeMillis();
            ret = pjp.proceed();
            time = System.currentTimeMillis() - time;
            System.out.printf("共耗时: %d 毫秒\n", time);
        } catch (Throwable throwable) {
            throw throwable;
        }
        return ret;
    }

    @After("execution(* com.yc.spring.aop.*.test(..))")
    public void advice(){
        System.out.println("----------advice--------");
    }

    /**
     *
     * try{
     *      @Before
     *      业务方法
     *      @AfterReturning
     * } catch (e){
     *      @AfterThrowing
     * } finally {
     *      @After
     * }
     *
     */

}
